package com.jahe.learn.netty4;

import com.jahe.learn.netty4.websocket.HeartBeatHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

/**
 * 支持连接心跳检测
 * @author: jahe.lai
 * @create: 2019-12-25 17:09
 */
public class HeartBeatServer02 {

    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            // 启动 和 配置属性相关的 辅助类
            ServerBootstrap bootstrap = new ServerBootstrap();
            // 配置相关属性
            bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    // handler 是针对 bossGroup 作配置的
                    .handler(new LoggingHandler(LogLevel.INFO))
                    // childHandler 是针对 workerGroup 作配置的
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new IdleStateHandler(30, 30, 50, TimeUnit.SECONDS))
                                    .addLast(new HeartBeatHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.bind(new InetSocketAddress(8899)).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}
